<?php
if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
/*********************************************************************************
 * SugarCRM is a customer relationship management program developed by
 * SugarCRM, Inc. Copyright (C) 2004-2010 SugarCRM Inc.
 * 
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU Affero General Public License version 3 as published by the
 * Free Software Foundation with the addition of the following permission added
 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
 * 
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
 * details.
 * 
 * You should have received a copy of the GNU Affero General Public License along with
 * this program; if not, see http://www.gnu.org/licenses or write to the Free
 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301 USA.
 * 
 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
 * 
 * The interactive user interfaces in modified source and object code versions
 * of this program must display Appropriate Legal Notices, as required under
 * Section 5 of the GNU Affero General Public License version 3.
 * 
 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
 * these Appropriate Legal Notices must retain the display of the "Powered by
 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
 * technical reasons, the Appropriate Legal Notices must display the words
 * "Powered by SugarCRM".
 ********************************************************************************/




require_once('include/Dashlets/DashletGenericChart.php');

class TasksByTypeDashlet extends DashletGenericChart 
{
//    public $tasks_date_start;
//    public $tasks_date_end;
    public $task_types = array();
    
    protected $_seedName = 'Tasks';
    
    /**
     * @see DashletGenericChart::__construct()
     */
    public function __construct($id, array $options = null) 
    {
        global $timedate;
/*        
        if(empty($options['tasks_date_start'])) 
            $options['tasks_date_start'] = date($timedate->get_db_date_time_format(), time());
        if(empty($options['tasks_date_end']))
            $options['tasks_date_end'] = date($timedate->get_db_date_time_format(), strtotime("+6 months", time()));
*/

		parent::__construct($id, $options);

        // load searchfields
        $classname = get_class($this);
        if ( is_file("custom/modules/Charts/Dashlets/$classname/$classname.data.php") ) {
            require("custom/modules/Charts/Dashlets/$classname/$classname.data.php");
            $this->_searchFields = $dashletData[$classname]['searchFields'];
        }

        // load language files
        $this->loadLanguage($classname, 'custom/modules/Charts/Dashlets/');

        if ( empty($options['title']) )
            $this->title = $this->dashletStrings['LBL_TITLE'];
    }

    public function isSugar6_2() {
    	global $sugar_config;
		if (str_begin($sugar_config['sugar_version'], "6.2")) {
			// compatible with Sugar 6.2
			return true;
		} else {
			// compatible with Sugar 5.5 and 6.1
			return false;
		}
	}

    /**
     * @see DashletGenericChart::displayOptions()
     */
    public function displayOptions()
    {
        global $app_list_strings;
        
        $selected_datax = array();
        if (count($this->task_types) > 0)
            foreach ($this->task_types as $key)
                $selected_datax[] = $key;
        else 
            $selected_datax = array_keys($app_list_strings['task_type_dom']);
        
        $this->_searchFields['task_types']['options'] = $app_list_strings['task_type_dom'];
        $this->_searchFields['task_types']['input_name0'] = $selected_datax;
        
        return parent::displayOptions();
    }
    
    /**
     * @see DashletGenericChart::display()
     */
    public function display() 
    {
		global $sugar_config, $current_user;

        if ($this->isSugar6_2()) {
			// compatible with Sugar 6.2
			require_once('include/SugarCharts/SugarChartFactory.php');
			$sugarChart = SugarChartFactory::getInstance();
		} else {
			// compatible with Sugar 5.5 and 6.1
			require_once('include/SugarCharts/SugarChart.php');
			$sugarChart = new SugarChart();
		}
		$sugarChart->base_url = array(
			'module' => 'Tasks',
			'action' => 'index',
			'query' => 'true',
			'searchFormTab' => 'advanced_search',
		);
	//        $sugarChart->url_params = array( 'assigned_user_id' => $current_user->id );		
		$sugarChart->group_by = $this->constructGroupBy();

		$dataset = $this->constructCEChartData($this->getChartData($this->constructQuery()));
		$sugarChart->setData($dataset);
		
		// Define Title
		$total = format_number($this->getHorizBarTotal($dataset), 0, 0, array('convert' => true));
		$total_unfinished_tasks_string = $total . $this->dashletStrings['LBL_TOTAL_UNFINISHED_TASKS'];
		$sugarChart->setDisplayProperty('title', $total_unfinished_tasks_string);

		// Define Subtitle
		$subtitle = $this->dashletStrings['LBL_NUMBER_OF_TASKS'];
		$sugarChart->setDisplayProperty('subtitle', $subtitle);

		// Define Chart Type
		$sugarChart->setDisplayProperty('type', 'horizontal bar chart');
				
		$xmlFile = $sugarChart->getXMLFileName($this->id);
		$sugarChart->saveXMLFile($xmlFile, $sugarChart->generateXML());

    	if ($this->isSugar6_2())
			return $this->getTitle('') . '<div align="center">' . $sugarChart->display($this->id, $xmlFile, '100%', '480', false). '</div>'. $this->processAutoRefresh();	
		else
			return $this->getTitle('') . '<div align="center">' . $sugarChart->display($this->id, $xmlFile, '100%', '480', false) . '</div><br />';
    }

	/**
     * awu: Bug 16794 - this function is a hack to get the correct sales stage order 
     * until i can clean it up later
     *
     * @param  $query string
     * @return array
     */
    private function getChartData(
        $query
        )
    {
    	global $app_list_strings, $db;
    	
    	$data = array();
    	$temp_data = array();
    	$selected_datax = array();
    	
        $tempx = $this->task_types;
        
        //set $datax using selected sales stage keys
        if (count($tempx) > 0) {
            foreach ($tempx as $key) {
                $datax[$key] = $app_list_strings['task_type_dom'][$key];
                array_push($selected_datax, $key);
            }
        }
        else {
            $datax = $app_list_strings['task_type_dom'];
            $selected_datax = array_keys($app_list_strings['task_type_dom']);
        }
        
        $result = $db->query($query);
        $row = $db->fetchByAssoc($result, -1, false);
        
        while($row != null){
        	$temp_data[] = $row;
        	$row = $db->fetchByAssoc($result, -1, false);
        }

		// reorder and set the array based on the order of selected_datax        
        foreach($selected_datax as $task_type){
        	foreach($temp_data as $key => $value){
        		if ($value['type'] == $task_type){
        			$value['type'] = $app_list_strings['task_type_dom'][$value['type']];
        			$value['key'] = $task_type;
        			$value['value'] = $value['type'];
        			$data[] = $value;
        			unset($temp_data[$key]);
        		}
        	}
        }
        return $data;
    }
    
    /**
     * @param  $dataset array
     * @return int
     */
    private function getHorizBarTotal(
        $dataset
        )
    {
    	$total = 0;
    	foreach($dataset as $value){
    		$total += $value;
    	}
    	
    	return $total;
    }
    
    /**
     * @param  $dataset array
     * @return array
     */
    private function constructCEChartData(
        $dataset
        )
    {
    	$newData = array();
    	foreach($dataset as $key=>$value){
    		$newData[$value['type']] = $value['total'];
    	}
    	return $newData;	
    }
    
	/**
     * @see DashletGenericChart::constructQuery()
     */
    protected function constructQuery() 
    {
        $query = "SELECT tasks.type,
			users.user_name,
                        tasks.assigned_user_id,
                        count( * ) AS total
                    FROM tasks 
			LEFT JOIN users ON tasks.assigned_user_id = users.id ";
        $query .= " WHERE tasks.status <> 'Completed' " .
			" AND tasks.status <> 'Deferred' ".
			" AND tasks.status <> 'Pending Input' ".
                        " AND tasks.deleted=0 ";
        if ( count($this->task_types) > 0 )
            $query .= " AND tasks.type IN ('" . implode("','",$this->task_types) . "') ";
        $query .= " GROUP BY tasks.type";

        return $query;
    }
    
    /**
     * @see DashletGenericChart::constructGroupBy()
     */
    protected function constructGroupBy()
    {
    	$groupBy = array('type_advanced', 'user_name');
//	array_push($groupBy, 'status_advanced[]');    	
    	return $groupBy; 
    }
}

?>
